# coding:utf-8
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import KernelDensity
from scipy import integrate
import pandas as pd
import pickle
from datetime import datetime

print("first we load data and sort it")
data = pd.read_table("../orders.tbl", sep='|')

# data.sort_values('o_totalprice', inplace=True)
# data.reset_index(drop=True, inplace=True)

print("finish data preprocess")

# 通常row_number应该与orderby一起使用，否则意义不大
# 使用此模型可以在不排序的情况下返回当前tuple的排名

# kde = KernelDensity(kernel='gaussian', bandwidth=2).fit(X)

with open('../kde.pkl', 'rb') as f:
    kde = pickle.load(f)


def f_p(*args):
    return np.exp(kde.score_samples(np.array(args).reshape(1, -1)))


def equal(y_min, y_max, num1, num2):
    return abs(num1 - num2) < (abs(float(y_max) - float(y_min)) / float(100000))


count = 0
result_list = []
time_list = []

start = datetime.now()

total_min = data['o_totalprice'].min()
total_max = data['o_totalprice'].max()
no = 200
x_min = total_min
x_max = total_max
while True:

    middle = (x_min + x_max) / 2
    ans = integrate.quad(f_p, total_min, middle, epsabs=10.0, epsrel=0.1)[0] * float(1500000)
    print("find range:{}~{}, ans:{}".format(x_min, x_max, ans))
    if equal(total_min, total_max, no, ans):
        print("find num:{}".format(ans))
        break
    elif ans > no:
        x_max = middle
    else:
        x_min = middle

end = datetime.now()
time_cost = (end - start).total_seconds()
print("time cost {}".format(time_cost))
